package com.shop.shoppingmall.service.impl;

import com.shop.shoppingmall.dao.ShInorderDao;
import com.shop.shoppingmall.dao.ShProportionDao;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.dao.ShWalletDao;
import com.shop.shoppingmall.entity.ShInorder;
import com.shop.shoppingmall.entity.ShProportion;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.entity.ShWallet;
import com.shop.shoppingmall.service.ShInorderService;
import com.shop.shoppingmall.service.ShIntegralService;
import com.shop.shoppingmall.service.ShSpecialCoinService;
import com.shop.shoppingmall.service.ShWalletService;
import com.shop.shoppingmall.util.UUIDGenerator;
import com.shop.shoppingmall.util.api.vo.Result;
import com.shop.shoppingmall.util.oConvertUtils;
import com.shop.shoppingmall.util.CommonConstant;
import com.shop.shoppingmall.util.api.vo.Result;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * (ShInorder)表服务实现类
 *
 * @author makejava
 * @since 2021-02-18 16:33:36
 */
@Service("shInorderService")
@Slf4j
@Transactional
public class ShInorderServiceImpl implements ShInorderService {
    @Resource
    private ShInorderDao shInorderDao;
    @Resource
    private ShWalletDao shWalletDao;
    @Resource
    private ShSpecialCoinService shSpecialCoinService;
    @Resource
    private ShIntegralService shIntegralService;
    @Resource
    private ShWalletService shWalletService;
    @Resource
    private ShUserDao shUserDao;
    @Resource
    private ShProportionDao shProportionDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShInorder queryById(String id) {
        return this.shInorderDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<ShInorder> queryAllByLimit(int offset, int limit) {

        int offset2 = (offset-1)*limit;

        return this.shInorderDao.queryAllByLimit(offset2, limit);
    }

    /**
     * 新增数据
     *
     * @param shInorder 实例对象
     * @return 实例对象
     */
    @Override
    public ShInorder insert(ShInorder shInorder) {
        this.shInorderDao.insert(shInorder);
        return shInorder;
    }

    /**
     * 修改数据
     *
     * @param shInorder 实例对象
     * @return 实例对象
     */
    @Override
    public ShInorder update(ShInorder shInorder) {
        this.shInorderDao.update(shInorder);
        return this.queryById(shInorder.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.shInorderDao.deleteById(id) > 0;
    }

    /**
     * 新增订单
     * @param shInorder
     * @return
     */
    int i=0;
    @Override
    public Result insertInOrder(ShInorder shInorder) {
        i=0;
        if( StringUtils.isNotBlank(shInorder.getInproductId()) && StringUtils.isNotBlank(shInorder.getAddId())){
            shInorder.setId(UUIDGenerator.generate());
            String salt = oConvertUtils.randomGen(16);
            shInorder.setOrderNumber(salt);
            shInorder.setOrderStatus("1");
            //判断
            List<ShProportion> shProportionList = shProportionDao.queryAll();
            ShUser shUser = shUserDao.selectShUserByUserId(shInorder.getUserId());
            ShWallet shWallet = shWalletDao.selectByUserId(shInorder.getUserId());
            if (shWallet == null) {
                return Result.error(CommonConstant.SC_OK_202, "未查到用户钱包信息");
            }
            if (shInorder == null){
                log.info("未查到该订单信息,订单号为"+shInorder.getOrderNumber());
                return Result.error(CommonConstant.SC_OK_202,"未查到该订单信息");
            }
            if(shWallet.getSpecialCoin().compareTo(shInorder.getOrderPrice()) == -1){
                log.info("专用币金额不足,订单号为"+shInorder.getOrderNumber()+"用户id"+shInorder.getUserId());
                return Result.error(CommonConstant.SC_OK_202,"专用币余额不足无法进行兑换");
            }
//            if(shInorder.getOrderStatus().equals("2")){
//                return Result.error(CommonConstant.SC_OK_202,"该订单已经支付过");
//            }
            int i = this.shInorderDao.insertInOrder(shInorder);
            if(i>0){
//                ShInorder shInorder = shInorderDao.queryByNumber(orderNumber);
                log.info("订单状态为"+shInorder.getOrderStatus());
                log.info("订单金额为"+shInorder.getOrderPrice()+"专用币余额为"+shWallet.getSpecialCoin());
                shWallet.setSpecialCoin(shWallet.getSpecialCoin().subtract(shInorder.getOrderPrice()));
                shWalletDao.update(shWallet);
                shSpecialCoinService.insertExpenditure(shInorder.getOrderPrice(),shInorder.getUserId(),"商品兑换");
                shInorder.setOrderStatus("2");
                shInorderDao.update(shInorder);


                /**
                 * 给当前用户自己分润
                 */

                log.info("给当前用户自己分润 积分为:"+new BigDecimal(50).multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000))+"" +
                        "用户id为"+shInorder.getUserId());
                shIntegralService.insertInCome(new BigDecimal(50).multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000)),shInorder.getUserId(),"","会员积分");
                //修改钱包积分数量
                shWalletService.updateIntegral(shInorder.getUserId(),new BigDecimal(50).multiply(shProportionList.get(0).getProportion()).multiply(new BigDecimal(10000)));
                //给当前用户上级分润
                ShUser sysUsersUp=shUserDao.selectCode(shUser.getSuperiorCode());//上级
                //当前用户存在上级
                if(sysUsersUp != null) {
                    eachLevel(sysUsersUp, shUser, new BigDecimal(50), shProportionList);
                }
                return Result.ok("兑换成功");
            }else{
                return Result.ok("新增订单失败");
            }
        }else{
            return Result.ok("新增订单失败,地址id和商品id不能为空");
        }


    }

    /**
     * 查询详情
     * @param id
     * @return 对象列表
     */
    @Override
    public ShInorder inquiryDetails(String id) {
        return shInorderDao.inquiryDetails(id);
    }


    /**
     * 查询多条数据 app不分页
     * @return 对象列表
     */
    @Override
    public List<ShInorder> queryAllByLimit2(String userId) {
        return this.shInorderDao.queryAllByLimit2(userId);
    }

    /**
     * 订单编号查询
     * @return 对象列表
     */
    @Override
    public ShInorder selectByOrderNum(String orderNumber) {
        return this.shInorderDao.selectByOrderNum(orderNumber);
    }

    @Override
    public Result payOrder(String orderNumber,String userId) {
//        i=0;
//
//        ShInorder shInorder = shInorderDao.queryByNumber(orderNumber);
//        ShWallet shWallet = shWalletDao.selectByUserId(userId);
//
//        if (shWallet == null) {
//            return Result.error(CommonConstant.SC_OK_202, "未查到用户钱包信息");
//        }
//        if (shInorder == null){
//            log.info("未查到该订单信息,订单号为"+orderNumber);
//            return Result.error(CommonConstant.SC_OK_202,"未查到该订单信息");
//        }
//        if(shWallet.getSpecialCoin().compareTo(shInorder.getOrderPrice()) == -1){
//            log.info("专用币金额不足,订单号为"+orderNumber+"用户id"+userId);
//            return Result.error(CommonConstant.SC_OK_202,"专用币余额不足无法进行兑换");
//        }
//        if(shInorder.getOrderStatus().equals("2")){
//            return Result.error(CommonConstant.SC_OK_202,"该订单已经支付过");
//        }
//        log.info("订单状态为"+shInorder.getOrderStatus());
//        log.info("订单金额为"+shInorder.getOrderPrice()+"专用币余额为"+shWallet.getSpecialCoin());
//        shWallet.setSpecialCoin(shWallet.getSpecialCoin().subtract(shInorder.getOrderPrice()));
//        shWalletDao.update(shWallet);
//        shSpecialCoinService.insertExpenditure(shInorder.getOrderPrice(),userId,"商品兑换");
//        shInorder.setOrderStatus("2");
//        shInorderDao.update(shInorder);
//
       return Result.ok("兑换成功");
    }

    public  void eachLevel(ShUser sysUsers1, ShUser shUser, BigDecimal rebate,List<ShProportion> shProportionList) {
        i =i+1;
        System.out.println(i);
        if(sysUsers1.getVipState().equals("1")){
            log.info("给当前用户上级分润 积分为:"+rebate.multiply(shProportionList.get(i).getProportion()).multiply(new BigDecimal(10000))+"" +
                    "用户id为"+sysUsers1.getId());
            shIntegralService.insertInCome(rebate.multiply(shProportionList.get(i).getProportion()).multiply(new BigDecimal(10000)),sysUsers1.getId(),shUser.getId(),"会员积分");
            shWalletService.updateIntegral(sysUsers1.getId(),rebate.multiply(shProportionList.get(i).getProportion()).multiply(new BigDecimal(10000)));
        }
        ShUser sysUsersUp=shUserDao.selectCode(sysUsers1.getSuperiorCode());//上级
        if(sysUsersUp != null) {
            if(i<=10){
                eachLevel(sysUsersUp, sysUsers1, rebate, shProportionList);
            }else{
                log.info("分润结束==========================================");
                return;
            }
        } else {
            log.info("分润结束==========================================");
            return;
        }
        log.info("分润结束==========================================");
        return;
    }
}
